package com.atguigu.bigdata.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.atguigu.bigdata.edu.realtime.app.BaseAppV1;
import com.atguigu.bigdata.edu.realtime.bean.TrafficPageViewBean;
import com.atguigu.bigdata.edu.realtime.common.Constant;
import com.atguigu.bigdata.edu.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/10/17 08:58
 */
public class Dws_02_DwsTrafficVcChArIsNewPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_02_DwsTrafficVcChArIsNewPageViewWindow().init(
            4002,
            2,
            "Dws_02_DwsTrafficVcChArIsNewPageViewWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 封装到一个 pojo 中
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚和
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resultStream);
    }
    
    private void writeToClickhouse(SingleOutputStreamOperator<TrafficPageViewBean> resultStream) {
        resultStream
            .addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_vc_ch_ar_is_new_page_view_window",
                                                     TrafficPageViewBean.class
            ));
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream) {
        // NoKeyBy 聚合:  开窗: WindowAll 每维度, 所有的数据在一起聚和, 窗口处理函数的并行度只能是 1
        // keyBy 聚合: 并行度没有限制
        
        // 窗口处理函数:
        // 增量: sum max min   reduce  aggregate
        // 全量: process
        
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofMillis(1))
            )
            .keyBy(bean -> bean.getCh() + "_" + bean.getAr() + "_" + bean.getVc() + "_" + bean.getIsNew())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean bean1,
                                                      TrafficPageViewBean bean2) throws Exception {
                        bean1.setPvCt(bean1.getPvCt() + bean2.getPvCt());
                        bean1.setSvCt(bean1.getSvCt() + bean2.getSvCt());
                        bean1.setUvCt(bean1.getUvCt() + bean2.getUvCt());
                        bean1.setDurSum(bean1.getDurSum() + bean2.getDurSum());
                        
                        return bean1;
                    }
                },
                // 泛型一: 表示输入. 前面的聚和 结果 的类型.
                new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,  // key 的值
                                        Context ctx,  // 上下文对象
                                        Iterable<TrafficPageViewBean> elements, // 存储的当前这个窗口最终聚合结果: 这个集和有且仅有一个值
                                        Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean bean = elements.iterator().next();
                        // 补充窗口开始和结束
                        bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                        
                        // 表示这个结果的统计时间
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
       return  stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {
                
                private ValueState<String> dateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
                }
                
                @Override
                public TrafficPageViewBean map(JSONObject obj) throws Exception {
                    
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    
                    String vc = common.getString("vc");
                    String ar = common.getString("ar");
                    String ch = common.getString("ch");
                    String isNew = common.getString("is_new");
                    Long ts = obj.getLong("ts");
                    Long  pvCt=1L;
                    Long  durSum=page.getLong("during_time");
                    Long svCt=0L;
                    String lastPageId = page.getString("last_page_id");
                    if (lastPageId==null || lastPageId.length()==0) {
                        svCt=1L;
                    }
                    Long uvCt=0L;
                    //状态中存储年月日，如果来的数据的日期和状态不一样，就是当天第一条 Long uvCt=1 更新状态，否则就不是第一条
                    String date = dateState.value();
                    String today = AtguiguUtil.toDate(ts);
                    if (!today.equals(date)) {
                        //更新状态
                        dateState.update(today);
                         uvCt=1L;
                    }


                    return new TrafficPageViewBean("", "",
                                                   vc, ch, ar, isNew,
                                                   uvCt, svCt, pvCt, durSum,
                                                   ts
                    );
                }
            });
    }
}
/*
版本-渠道-地区-访客类别  粒度: 维度
会话数 页面浏览数 浏览总时长 独立访客数

数据源:
    会话数 session
        找到会话记录(开启一个新的页面)
        
        页面日志:
            last_page_id =null
            
    页面浏览数: pv
        页面日志
            来一条对 pv 贡献 1
            
    浏览总时长:
        页面日志
            during_time
    
    独立访客数: uv
        页面日志
        
        当日的独立访客数
        
        当日每个用户的第一条访问记录找
        
        每个用户的第一条记录
            按照 uid 分组. 使用状态: 存储用户最后一次访问日期
                今天第一次访问: 状态没值, 这条记录保留. 状态存入今天的日期
                今天第二,3,4,.. 访问: 今天与状态是否相等, 如果相等,就不是今天的第一次
                
                到的明天了: 年月日变成 18 日, 状态还是 17 日, 所以保留这条数据
                ...
-------------
每来一条数据就判断:
    把数据封装到一个 POJO 中
    还要 keyBy: uid
    sv     pv     uv    dur_time
    
    1/0    1      0/1     10000
 
开窗聚和:
    keyBy:版本-渠道-地区-访客类别
    聚合: 四个指标
    
 写出 clickhouse 中:
    ....


 */